package com.fling.abcde.activity;

import static com.fling.abcde.BaseApplication.sContext;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.base.gensture.widget.LockPatternView;
import com.fling.abcde.BaseApplication;
import com.fling.abcde.R;
import com.fling.abcde.base.BaseActivity;
import com.fling.abcde.databinding.ActivitySplashBinding;
import com.lib.common.bean.BaseResp;
import com.lib.okhttp.NetRequest;
import com.lib.okhttp.annotation.CacheType;
import com.lib.smartimage.SmartImageView;
import com.lib.utils.AppUtils;
import com.lib.utils.FileUtils;
import com.lib.utils.SPUtils;
import com.lib.utils.XLog;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import me.jessyan.autosize.internal.CancelAdapt;

/**
 * @author FengLing
 * Created on 2017-07-27 21:42
 */
public class SplashActivity extends BaseActivity<ActivitySplashBinding> implements CancelAdapt {

    private static final int MSG_QUERY = 0;
    private static final int MSG_TO_MAIN = 1;

    private InnerHandler mHandler = new InnerHandler(this);
    private SmartImageView mImg;
    private AlertDialog mAlertDialog;
    private DownloadManager mDownManager;
    private File mApkFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreenTranslucent(true);
        mImg = findViewById(R.id.img);
        mImg.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                v.setVisibility(View.GONE);
                return true;
            }
        });
        thisBinding.lpv.setOnPatternListener(new LockPatternView.OnPatternListener() {
            @Override
            public void onPatternStart() {

            }

            @Override
            public void onPatternComplete(List<LockPatternView.Cell> cells) {
                thisBinding.lpi.setIndicator(cells);
                XLog.i("cells.toArray(): " + cells.toArray());

                MainActivity.start(SplashActivity.this, MainActivity.class);
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getTodayOilPrice();
    }

    private void getTodayOilPrice() {
        String url = "https://httpbin.org/post";
//        String url = "https://www.mxnzp.com/api/oil/search?province=%E5%B9%BF%E4%B8%9C&app_id=yqjvi1maofwfijsd&app_secret=PW7dhLlXCLLEuGjq7jE4OU4QZ2QL2Asc";

        NetRequest.newInstance()
                .setCacheType(CacheType.AUTO)
                .setUrl(url)
                .doPost()
                .addHead("head", "head")
                .setParamJson("{\"qwe\", \"qwer\"}")
                .doReq(mNetManager, String.class);
    }

    @Override
    public void onProgressChanged(Integer progress) {
        super.onProgressChanged(progress);
        XLog.i("progress = " + progress);
        showLoading(progress + "");
    }

    @Override
    public void onDataChanged(BaseResp baseResp) {
        super.onDataChanged(baseResp);
        hideLoading();
        XLog.i(Thread.currentThread().getName() + ", baseBean = " + baseResp);
        String imageUrl = "https://dss3.baidu.com/-rVXeDTa2gU2pMbgoY3K/it/u=4096191987,3208811386&fm=202&mola=new&crop=v1";
        mImg.setImageUrl(imageUrl);

        if (true) {
            if (mAlertDialog == null) {
                String url = imageUrl;
                AlertDialog.Builder builder = new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("已检测到新版本")
                        .setPositiveButton(getString(android.R.string.ok), (dialog, which) -> {
//                            toDownLoadApk(url);
                        });
                if (true) {
                    builder.setNegativeButton(getString(android.R.string.cancel), (dialog, which) -> {
                        mHandler.sendEmptyMessageDelayed(MSG_TO_MAIN, 1000);
                    });
                }
                mAlertDialog = builder.create();
                mAlertDialog.setCanceledOnTouchOutside(false);
            }
            mAlertDialog.show();
            return;
        }
    }

    private void toDownLoadApk(String url) {

        String downloadApkPath = FileUtils.getCacheDir(sContext).getAbsolutePath();
        mApkFile = new File(downloadApkPath, "APK/1.0.0.apk");

        if (mApkFile.exists()) {
            int downLoadApkSize = SPUtils.getSP().getInt(SPUtils.KEY_LAST_DOWNLOADED_SIZE, -1);
            if (downLoadApkSize == mApkFile.length()) {
                AppUtils.installApp(this, mApkFile);
                BaseApplication.safeExitApp();
                return;
            } else {
                if (!mApkFile.delete()) {
                    mApkFile.delete();
                }
            }
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setTitle(getString(R.string.app_name));
        request.setDescription("更新包正在下载...");
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");
        //设置文件存放目录
        request.setDestinationUri(Uri.fromFile(mApkFile));
        request.setVisibleInDownloadsUi(true);
        mDownManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        long id = mDownManager.enqueue(request);
        Message msg = Message.obtain();
        msg.what = MSG_QUERY;
        msg.obj = id;
        mHandler.sendMessageDelayed(msg, 1000);
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        super.onDestroy();
    }

    private static class InnerHandler extends Handler {

        private SplashActivity mActivity;
        private DownloadManager.Query mQuery;
        private Cursor mCursor;

        private InnerHandler(SplashActivity activity) {

            mActivity = (new WeakReference<>(activity)).get();
            mQuery = new DownloadManager.Query();
        }

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_QUERY: {
                    //根据id进行查询
                    if (mCursor == null) {
                        mCursor = mActivity.mDownManager.query(mQuery.setFilterById((long) msg.obj));
                    }
                    if (mCursor != null && mCursor.moveToFirst()) {
                        //已经下载的字节数
                        int bytesDownload = mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        //文件的总的字节数
                        int bytesTotal = mCursor.getInt(mCursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        // mActivity.mProgressDialog.setProgress((int) (bytesDownload * 1.0 / bytesTotal * 100));
                        if (bytesDownload >= bytesTotal) {
                            SPUtils.getSP().edit()
                                    .putInt(SPUtils.KEY_LAST_DOWNLOADED_SIZE, bytesTotal)
                                    .apply();

                            mCursor.close();
                            mCursor = null;
                            mQuery = null;
                            AppUtils.installApp(mActivity, mActivity.mApkFile);
                            BaseApplication.safeExitApp();
                            return;
                        }
                        Message msgQuery = Message.obtain();
                        msgQuery.what = MSG_QUERY;
                        msgQuery.obj = msg.obj;
                        sendMessageDelayed(msgQuery, 1000);
                    } else {
                        Toast.makeText(mActivity, "下载异常", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
                case MSG_TO_MAIN: {
                    Intent intent = new Intent();
                    intent.setClass(mActivity, MainActivity.class);
                    mActivity.startActivity(intent);
                    mActivity.finish();
                }
                break;
            }
        }
    }
}